package com.adam.springbucks.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.adam.springbucks.cof.entity.Coffee;
import com.adam.springbucks.mapper.CoffeeMapper;
import com.adam.springbucks.service.CoffeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@CacheConfig(cacheNames = "coffee")//开启缓存
public class CoffeeServiceImpl implements CoffeeService {

	@Autowired
	private CoffeeMapper coffeeMapper;

	@Override
	@Cacheable
	public List<Coffee> findAllCoffees() {
		return coffeeMapper.findAllCoffees();
	}

	@Override
	@Cacheable(value = "coffee")
	public List<Coffee> findCoffeesByIds(List<Long> list) {

		if (list.size() == 0) {
			return null;
		}

		List<Coffee> coffeeObject = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			long id = (long) list.get(i);
			coffeeObject.add(coffeeMapper.findById(id));
		}
		return coffeeObject;
	}

	@Override
	@CacheEvict
	public void reloadCoffee() {
	}

	@Override
	@Cacheable(value = "coffee", key = "#id")
	public Coffee findById(Long id) {
		return coffeeMapper.findById(id);
	}

	@Override
	@Transactional //事务支持
	public int insertCoffee(String name, BigDecimal price) {
		return coffeeMapper.insertCoffee(Coffee.builder().name(name).price(price).build());
	}

	@Override
	@Transactional //事务支持
	@CacheEvict(value = "deleteCoffee",key = "#id") //清除缓存
	public int deleteCoffee(Long id) {
		return coffeeMapper.deleteCoffee(id);
	}

	@Override
	@Transactional //事务支持
	@CacheEvict(value = "updateCoffee",key = "#id") //清除缓存
	public int updateCoffee(Long id, String name, BigDecimal price) {
		return coffeeMapper.updateCoffee(id, name, price);
	}

	@Override
	public List<Coffee> findAllWithParam(int pageNum, int pageSize) {
		return coffeeMapper.findAllWithParam(pageNum, pageSize);
	}
}
